package net.lab1024.sa.gateway.predicate;

import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * 灰度路由
 */
@Component
public class GrayRoutePredicateFactory extends AbstractRoutePredicateFactory<GrayRoutePredicateFactory.Config> {
    public GrayRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exchange -> {
            // 从请求头获取染色标签
            List<String> tags = exchange.getRequest().getHeaders().get("X-Traffic-Tag");
            if (tags == null || tags.isEmpty()) return false;
            // 匹配允许的标签
            return config.getAllowTags().contains(tags.get(0));
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("allowTags"); // 配置参数顺序
    }

    /**
     * 过滤器配置
     */
    @Data
    public static class Config {
        /**
         * 允许的染色标签（如["gray", "test"]）
         */
        private List<String> allowTags;
    }

}

